<?php

namespace App\Strategys\Message;

use App\Services\ChatRoomService;
use App\Traits\MessageResponseTraits;

abstract class Message {

    use MessageResponseTraits;

    /**
     * 连接对象
     * @param object $ws
     */
    protected $ws;

    /**
     * 连接编号
     * @param int $fd
     */
    protected $fd;

    /**
     * 对象初始化
     * @param object $ws
     * @param int $fd
     */
    public function __construct(object $ws, int $fd) {
        $this->ws = $ws;
        $this->fd = $fd;
    }

    /**
     * 用户上线处理
     * @param int $user_id
     * @return string
     */
    protected function userOnline(int $user_id)
    {
        $user_info = (new ChatRoomService())->userOnline($this->fd, $user_id);
        if (empty($user_info)) {
            $this->ws->push($this->fd, $this->failed(['message' => '当前时间客服正忙，请稍后再试~']));
        } else {
            // 用户推送成功消息
            $this->ws->push($this->fd, $this->success($user_info));

            // 向客服推送 用户上线通知
            $this->ws->push($user_info['customer']['fd'], $this->success($user_info, 'userOnline'));
        }
    }

    /**
     * 发送消息公共方法
     * @param array $message_data
     * @return void
     */
    protected function sendMessagePublic(array $message_data, $msg_type = 1)
    {
        $service = new ChatRoomService();

        // 获取当前聊天的客服和用户通道
        $room_id   = $message_data['room_id'];
        $room_info = $service->getRoomInfo($room_id);

        if (!empty($room_info)) {
            $room_info = explode('-', $room_info);
            $msg_data  = [
                'room_id'   => $message_data['room_id'],
                'message'   => $message_data['data']['message'],
                'user_type' => $message_data['user_type']
            ];

            $fd = $msg_type === 1 ? $room_info[0] : $room_info[1];
            // 缓存聊天消息内容
            $service->cacheChatMessage($msg_data);
            $this->ws->push($fd, $this->success($msg_data, 'message'));
        }
    }

    /**
     * 客服下线
     * @param array $user_info
     * @return void
     */
    protected function userLogoff(array $user_info)
    {
        (new ChatRoomService())->userLogoff($user_info);
        $this->ws->push($user_info['customer']['fd'], $this->success(['room_id' => $user_info['room_id']], 'userLogoff'));
    }

    /**
     * 聊天用户上线处理
     * @param int $user_id
     * @return void
     */
    abstract function online(int $user_id = 0);

    /**
     * 用户消息发送处理
     * @param array $data
     * @return void
     */
    abstract function sendMessage(array $data);

    /**
     * 用户关闭聊天处理
     * @param array $user_info
     * @return void
     */
    abstract function close(array $user_info);
}
